import { getDicts } from '@/api/system/dict/data';
import { useDictStore } from '@/store/modules/dict';
import { listColumn } from '@/api/system/column/index'
import { updateColumn, addColumn } from '@/api/system/column/index'
/**
 * 获取字典数据
 */
export const useDict = (...args: string[]): { [key: string]: DictDataOption[] } => {
  const res = ref<{
    [key: string]: DictDataOption[];
  }>({});
  return (() => {
    args.forEach(async (dictType) => {
      res.value[dictType] = [];
      const dicts = useDictStore().getDict(dictType);
      if (dicts) {
        res.value[dictType] = dicts;
      } else {
        await getDicts(dictType).then((resp) => {
          res.value[dictType] = resp.data.map(
            (p): DictDataOption => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass })
          );
          useDictStore().setDict(dictType, res.value[dictType]);
        });
      }
    });
    return res.value;
  })();
};

/** 获取column列数据 */
export const useColumn = async (columnName: string) => {
  const { data } = await listColumn({ columnName })
  data.forEach((item: any) => item.columnCustom = JSON.parse(item.columnCustom))
  // 默认colmun
  const leftdatas = data.filter((item: any) => item.isDefault == 1)
  // 个性化colmun集合
  const rightDatas = data.filter((item: any) => item.isDefault == 0)

  // 防止个性化后 默认列删除某一项列数据
  if (rightDatas.length > 0) {
    var rightDatasFilter = rightDatas[0].columnCustom.filter((item: any) => {
      return leftdatas[0].columnCustom.findIndex((it: any) => item.label == it.label) !== -1
    })
  }

  const colmuns = rightDatas.length > 0 ? {
    ...rightDatas[0],
    columnCustom: rightDatasFilter,
  } : leftdatas[0]
  return colmuns
}

/** 更新列设置 */
export const useColumnUpdate = async (columnData: any, pageSize: any) => {
  if (columnData.isDefault == '1') {
    await addColumn({ ...columnData, isDefault: '0', columnPageSize: pageSize, columnCustom: JSON.stringify(columnData.columnCustom) })
  } else {
    await updateColumn({ ...columnData, columnPageSize: pageSize, columnCustom: JSON.stringify(columnData.columnCustom) })
  }
}
